package com.haidong.web;

import com.haidong.pojo.User;
import com.haidong.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先获取账号密码,然后调用登录方法,登录成功后,跳转到登录页面并预写入当前用户信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = service.login(username,password);
        if(user!=null){
            //登录成功之后要创建cookie并设置存活时间,记住用户名和密码
            if("1".equals(req.getParameter("remember"))){
                Cookie cookieName = new Cookie("username",username);
                Cookie cookiePassword = new Cookie("password",password);
                cookieName.setMaxAge(60*60*24*7);
                cookiePassword.setMaxAge(60*60*24*7);
                resp.addCookie(cookieName);
                resp.addCookie(cookiePassword);
            }


            //登录成功,重定向到品牌页面并动态显示当前用户信息
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            resp.sendRedirect(req.getContextPath()+"/selectAllServlet");
        }else{
            //登录失败就响应错误信息
            req.setAttribute("login_msg","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
